//
//  IconViewController.m
//  Zhai
//
//  Created by 周文静 on 16/8/5.
//  Copyright © 2016年 lechuangshidai. All rights reserved.
//

#import "IconViewController.h"
#import "IconCell.h"
#import "OtherCell.h"
#import "UIImage+DY.h"
#import "NSObject+SelectedVc.h"

#import "SetNameViewController.h"
#import "CityViewController.h"
#import "DeclarationViewController.h"
#import "UIImageView+WebCache.h"
#import "AFManager.h"
#import "PersonalData.h"
#import "PersonalShowInfo.h"
//#import <UIImageView+WebCache.h>
@interface IconViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    PersonalData *_personalData;
    
}
@property (weak, nonatomic) IBOutlet UITableView *iconTable;

@property (strong ,nonatomic)UIImagePickerController *imagePikcerController;

@property (strong,nonatomic) UIImageView *iconImage;

@property (strong,nonatomic)  NSString *strName;

@property (strong,nonatomic) NSArray *selfDataArr;

@property (strong, nonatomic) NSMutableDictionary *detailDic;//选项列表


@end

@implementation IconViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"修改";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveBtnAct)];
    
        self.detailDic =[NSMutableDictionary dictionaryWithCapacity:10];

    [self setExtraCellLineHidden:_iconTable];
    
    [self getRequestPersonalShow];
}
-(void)getRequestPersonalShow
{
    NSLog(@"url===%@",[NSString stringWithFormat:Personal_InforShow_URL,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]]);
    [AFManager getReqURL:[NSString stringWithFormat:Personal_InforShow_URL,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]] block:^(id infor) {
        NSLog(@"infor===%@",infor);
        PersonalShowInfo *showInfo = [PersonalShowInfo personalCodeDictionary:infor];
        _personalData = [PersonalData personalDataDictionary:showInfo.data];

        [_iconTable reloadData];
    } errorblock:^(NSError *error) {
        
    }];
}
-(void)saveBtnAct
{
//        NSLog(@"self.detailDic  = %@",self.detailDic );
//    [self.navigationController popViewControllerAnimated:YES];
    [self postUpdatePersonalInfoRequest];
}
-(void)postUpdatePersonalInfoRequest
{
    NSMutableDictionary *bodyDic = [[NSMutableDictionary alloc] init];
    [bodyDic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"] forKey:@"id"];
    [bodyDic setObject:self.imageUrl forKey:@"head_pic"];
    [bodyDic setObject:self.nameStr forKey:@"nickname"];
    [bodyDic setObject:_personalData.sex forKey:@"sex"];
    [bodyDic setObject:self.areaStr forKey:@"area"];
    [bodyDic setObject:self.autoStr forKey:@"auto"];
    NSLog(@"bodyDic === %@",bodyDic);
    [AFManager postReqURL:XINXIXIUGAI reqBody:bodyDic block:^(id infor) {
        NSLog(@"updateInfor===%@",infor);
    }];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 15;
    }else{
        
        return 0.01;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return 4;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 80;
    }else{
        
        return 62;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        IconCell *cell = [IconCell iconViewCellWithTableView:tableView];
        self.iconImage = cell.iconImage;
        
        [cell.iconImage setImageWithURL:[NSURL URLWithString:_personalData.head_pic] placeholderImage:[UIImage imageNamed:@"fx-tx5"]];
        self.imageUrl = _personalData.head_pic;
        _imagePikcerController = [[UIImagePickerController alloc]init];
        _imagePikcerController.delegate = self;
        
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            _imagePikcerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        }else{
            _imagePikcerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        
        cell.iconImage.userInteractionEnabled = YES;
        
        [self saveImage:[UIImage imageNamed:@"me"]];


        return cell;
    }else{
        
        OtherCell *cell = [OtherCell otherViewCellWithTableView:tableView];
        
        NSArray *nameArr = @[@"名字",@"性别",@"地区",@"聊天宣言"];
        cell.nameLabel.text = nameArr[indexPath.row];
        if(indexPath.row == 0)
        {
            cell.selecteLabel.text = _personalData.nickname;
            self.nameStr = cell.selecteLabel.text;
        }

        if (indexPath.row == 1)
        {
            if ([_personalData.sex isEqualToString:@"0"])
            {
                cell.selecteLabel.text = @"女";
                self.sexStr = cell.selecteLabel.text;
            }
            else
            {
                cell.selecteLabel.text = @"男";
                self.sexStr = cell.selecteLabel.text;
            }
            
            cell.jianjianImage.hidden = YES;
        }
        if (indexPath.row == 2)
        {
            if ([_personalData.area isEqual:[NSNull null]])
            {
                cell.selecteLabel.text = @"";
                self.areaStr = cell.selecteLabel.text;
            }
            else
            {
                cell.selecteLabel.text = _personalData.area;
               NSLog(@"str===%@",cell.selecteLabel.text);
                self.areaStr = cell.selecteLabel.text;
            }
            
        }
        if (indexPath.row == 3)
        {
            if ([_personalData.area isEqual:[NSNull null]])
            {
                cell.selecteLabel.text = @"";
                self.autoStr = cell.selecteLabel.text;
            }
            else
            {
                cell.selecteLabel.text = _personalData.autoStr;
//                NSLog(@"str===%@",cell.selecteLabel.text);
                self.autoStr = cell.selecteLabel.text;
            }
            
        }
        return cell;
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        //弹出提示框
        [self setAlertAction];
    }else{
        OtherCell *otherCell = [tableView cellForRowAtIndexPath:indexPath];
        switch (indexPath.row) {
            case 0:
                //名字
                [self getName:otherCell];
                break;
            case 1:
                //性别
                break;
            case 2:
                //地区
                [self setArea:otherCell];
                break;
            case 3:
                //聊天宣言
                [self setDeclaration:otherCell];
                break;
            default:
                break;
        }
    }
}


-(void)getName:(OtherCell *)nameCell
{
    SetNameViewController *setNameVC = [[SetNameViewController alloc]initWithNibName:@"SetNameViewController" bundle:nil];
    setNameVC.nameStr = _personalData.nickname;
    [self.navigationController pushViewController:setNameVC animated:YES];
    
    [setNameVC nameText:^(NSString *nameTextData) {
     
        nameCell.selecteLabel.text = nameTextData;
        self.nameStr = nameTextData;
        NSLog(@"name===%@",nameTextData);
        
        [self.detailDic setObject:nameTextData forKey:@"name"];
        
    }];

}


-(void)setArea:(OtherCell *)cityCell
{
    CityViewController *cityVC = [[CityViewController alloc]initWithNibName:@"CityViewController" bundle:nil];
    [self.navigationController pushViewController:cityVC animated:YES];
    
    [cityVC cityBlock:^(NSString *city) {
        
        cityCell.selecteLabel.text = city;
        self.areaStr = city;
        
         [self.detailDic setObject:city forKey:@"area"];
    }];
    
}

-(void)setDeclaration:(OtherCell *)declarationCell
{
    DeclarationViewController *declarationVC = [[DeclarationViewController alloc]initWithNibName:@"DeclarationViewController" bundle:nil];
    [self.navigationController pushViewController:declarationVC animated:YES];

    [declarationVC declarationText:^(NSString *declarationText) {
        
        declarationCell.selecteLabel.text = declarationText;
        self.autoStr = declarationText;
         [self.detailDic setObject:declarationText forKey:@"declaration"];
       
    }];
}

-(void)setAlertAction
{
    [NSObject wj_selectedVcWithTitle:@"请选择图片" andTitleExplain:@"" andFirstSel:@"拍照" andSecondSel:@"从手机相册选择" andSelfVc:self andPresentStyle:JSPresentFromBottom andBackFirtsSelBlock:^(NSString *userSelStr) {
           [self openCamera];
        
    } andBackSecondSelBlock:^(NSString *userSelStr) {
         [self openAlbum];
    }];
}


//打开照相机
-(void)openCamera
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return;
    
    UIImagePickerController *ipc = [[UIImagePickerController alloc]init];
    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
    ipc.delegate = self;
    ipc.allowsEditing = YES;
    [self presentViewController:ipc animated:YES completion:nil];
}

//打开相册
-(void)openAlbum
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
    
    UIImagePickerController *ipc = [[UIImagePickerController alloc]init];
    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    ipc.delegate = self;
    ipc.allowsEditing = YES;
    [self presentViewController:ipc animated:YES completion:nil];
}

#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [self uploadImage:image];
    if(self.imagePikcerController.sourceType == UIImagePickerControllerSourceTypeCamera) {
        [self saveImage:image];
    }
    CGSize size = CGSizeMake(60, 60);
    NSData *cutData = [UIImage imageWithImage:image scaledToSize:size];
    _iconImage.image = [UIImage circleWithImage:[UIImage imageWithData:cutData] borderWidth:3.5 borderColor:[UIColor whiteColor]];
    
    
    [self.detailDic setObject:cutData forKey:@"icon"];

}
-(void)uploadImage:(UIImage *)image
{
    NSData *data=UIImageJPEGRepresentation(image, 1);
    [AFManager upLoadpath:KURL_FORMAT(LOCAL_HOST_URL,  Upload_Image_Url) reqBody:nil file:data fileName:@"file" fileType:@"image/jpg" block:^(id infor) {
        NSLog(@"====%@",infor);
        NSString *inforStr = [infor stringByReplacingOccurrencesOfString:@"\\" withString:@""];
        NSString *inforStr2 = [inforStr stringByReplacingOccurrencesOfString:@"\"" withString:@""];
        self.imageUrl = inforStr2;
        //        "http:\/\/139.224.43.42\/zhai\/Uploads\/18b9c171ee7bd29789670f66721b5984.png"
        NSLog(@"url===%@",self.imageUrl);
    } errorBlock:^(NSError *error) {
        
    }];
}

- (void)saveImage:(UIImage *)image{
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    

    
}



//隐藏table多余的线
- (void)setExtraCellLineHidden: (UITableView *)tableView{
    
    UIView *view =[ [UIView alloc]init];
    
    view.backgroundColor = [UIColor whiteColor];
    
    [tableView setTableFooterView:view];
    
    [tableView setTableHeaderView:view];
    
}

@end
